package com.qf.fengmimall.config;

import com.qf.fengmimall.constant.Constants;
import com.qf.fengmimall.shiro.CustomRealm;
import com.qf.fengmimall.shiro.JwtShiroFilter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘欣
 * @createTime 2023/2/9 19:03
 * @description
 */
@Configuration
public class ShiroConfig {

    @Autowired
    private ShiroProperties shiroProperties;

    /**
     *设置 starter依赖自动添加的  securityManager 对象
     *设置要使用的所有shiro的过滤器
     * 设置url和过滤器的匹配关系
     * @param securityManager
     * @param ShiroFilterChainDefinition
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager, ShiroFilterChainDefinition ShiroFilterChainDefinition) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(securityManager);

        HashMap<String, Filter> filterHashMap = new HashMap<>();

        filterHashMap.put("jwt", new JwtShiroFilter());

        filterHashMap.put("anon", new AnonymousFilter());

        shiroFilterFactoryBean.setFilters(filterHashMap);

        Map<String, String> filterChainMap = ShiroFilterChainDefinition.getFilterChainMap();

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);

        return shiroFilterFactoryBean;
    }


    /**
     * 配置shiro拦截路径
     *
     * @return
     */
    @Bean
    public ShiroFilterChainDefinition filterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        String[] anonUrls = shiroProperties.getAnonUrls();
        for (String anonUrl : anonUrls) {
            definition.addPathDefinition(anonUrl, "anon");
        }
//        definition.addPathDefinition("/**", "authc");
        return definition;
    }

    @Bean
    public Realm realm() {
        CustomRealm customRealm = new CustomRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashIterations(Constants.HASHCOUNT);
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return customRealm;
    }
}
